package com.tencent.qcloud.tuikit.tuichat.ui.GoodsList;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.core.view.WindowInsetsControllerCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cqyc.network.Response;
import com.cqyc.network.getid.GetMyInformationBox;
import com.cqyc.network.http.HttpUtil;
import com.cqyc.network.http.NConfig;
import com.cqyc.network.model.GoodsInfo;
import com.cqyc.network.utils.Utils;
import com.google.gson.Gson;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.tencent.qcloud.tuicore.TUICore;
import com.tencent.qcloud.tuikit.tuichat.R;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;

//商品列表页面
public class GoodsListActivity extends AppCompatActivity implements View.OnClickListener, OnRefreshLoadMoreListener {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_list);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(getResources().getColor(R.color.white));
            getWindow().setNavigationBarColor(getResources().getColor(com.tencent.qcloud.tuicore.R.color.navigation_bar_color));
            int vis = getWindow().getDecorView().getSystemUiVisibility();
            vis |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            vis |= View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;
            getWindow().getDecorView().setSystemUiVisibility(vis);
        }
        initView();
    }

    //1销量倒叙，2销量升序，3上新，4价格倒叙，5价格升序

    private int status = 0;//价格1升0降
    private int status1 = 1;//销量升降
    private int type = 1;
    private String name = "";
    private String goodsStatus;
    private SmartRefreshLayout smartLayout;
    private RecyclerView recyclerView;
    private GoodsAdapter adapter;
    private String mchId;
    private EditText editText;
    private View imClose, txCancel;

    private TextView tx1, tx2, tx3;
    private ImageView img1, img11, img2, img3, img4;
    private final int limit = 20;
    private int page = 1;

    private void initView() {
        smartLayout = findViewById(R.id.smart_layout);
        imClose = findViewById(R.id.im_close);
        txCancel = findViewById(R.id.tx_cancel);
        imClose.setOnClickListener(this);
        txCancel.setOnClickListener(this);
        editText = findViewById(R.id.edit_text);
        //在该Editview获得焦点的时候将“回车”键改为“搜索”
        editText.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        editText.setInputType(EditorInfo.TYPE_CLASS_TEXT);
        //不然回车【搜索】会换行
        editText.setSingleLine(true);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence != null && charSequence.length() > 0) {
                    imClose.setVisibility(View.VISIBLE);
                } else {
                    imClose.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if ((actionId == EditorInfo.IME_ACTION_UNSPECIFIED || actionId == EditorInfo.IME_ACTION_SEARCH) && keyEvent != null) {
                    //点击搜索要做的操作
                    txCancel.setVisibility(View.VISIBLE);
                    page = 1;
                    name = textView.getText().toString();
                    loadGoods();
                    return true;
                }
                return false;
            }
        });

        findViewById(R.id.back).setOnClickListener(this);
        findViewById(R.id.bt_1).setOnClickListener(this);
        findViewById(R.id.bt_2).setOnClickListener(this);
        findViewById(R.id.bt_3).setOnClickListener(this);
        tx1 = findViewById(R.id.tx_1);
        tx2 = findViewById(R.id.tx_2);
        tx3 = findViewById(R.id.tx_3);
        img1 = findViewById(R.id.img_1);
        img11 = findViewById(R.id.img_11);
        img2 = findViewById(R.id.img_2);
        img3 = findViewById(R.id.img_3);
        img4 = findViewById(R.id.img_4);
        recyclerView = findViewById(R.id.recycler);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        adapter = new GoodsAdapter(this);
        adapter.setOnSendGoods(new GoodsAdapter.OnSendGoods() {
            @Override
            public void sendGoods(GoodsInfo data) {
                Intent intent = new Intent();
                intent.putExtra("data", new Gson().toJson(data));
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        });
        adapter.setOnItemGoods(new GoodsAdapter.OnItemGoods() {
            @Override
            public void onItemGoods(GoodsInfo data) {
                Bundle bundle = new Bundle();
                Map<String, String> map = new HashMap<>();
                map.put("token", GetMyInformationBox.INSTANCE.getToken());
                map.put("app_id", GetMyInformationBox.INSTANCE.getAppId());
                map.put("android_version_code", GetMyInformationBox.INSTANCE.getVersion());
                map.put("platform", "2");

                String path = Utils.Companion.buildUrl(data.getWebUrl(), map);
                bundle.putString(NConfig.Companion.getWebViewUrl(), path);
                TUICore.startActivity(NConfig.Companion.getWebName(), bundle);
            }
        });
        recyclerView.setAdapter(adapter);

        smartLayout.setOnRefreshLoadMoreListener(this);

        img11.setImageResource(R.drawable.ic_s3);
        mchId = getIntent().getStringExtra("id");
        mchId = NConfig.Companion.getRealId(mchId);

        page = 1;
        name = "";
        goodsStatus = "2";
        loadGoods();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.back) {
            finish();
        } else if (id == R.id.bt_1) {
            if (type != 1) {
                type = 1;
                img11.setImageResource(R.drawable.ic_s3);
                tx2.setTypeface(Typeface.DEFAULT);
                img2.setVisibility(View.INVISIBLE);
                tx3.setTypeface(Typeface.DEFAULT);
                img3.setImageResource(R.drawable.ic_s1);
                img4.setVisibility(View.INVISIBLE);

                tx1.setTypeface(Typeface.DEFAULT_BOLD);
                img1.setVisibility(View.VISIBLE);

                status1 = 1;
            } else {
                status1 = status1 == 0 ? 1 : 0;
                img11.setImageResource(status1 == 0 ? R.drawable.ic_s2 : R.drawable.ic_s3);
            }
            page = 1;
            name = "";
            goodsStatus = status1 == 0 ? "1" : "2";
            loadGoods();
        } else if (id == R.id.bt_2) {
            if (type != 2) {
                type = 2;
                tx1.setTypeface(Typeface.DEFAULT);
                img1.setVisibility(View.INVISIBLE);
                img11.setImageResource(R.drawable.ic_s1);
                tx3.setTypeface(Typeface.DEFAULT);
                img3.setImageResource(R.drawable.ic_s1);
                img4.setVisibility(View.INVISIBLE);

                tx2.setTypeface(Typeface.DEFAULT_BOLD);
                img2.setVisibility(View.VISIBLE);

                page = 1;
                name = "";
                goodsStatus = "3";
                loadGoods();
            }
        } else if (id == R.id.bt_3) {
            if (type != 3) {
                type = 3;
                tx1.setTypeface(Typeface.DEFAULT);
                img1.setVisibility(View.INVISIBLE);
                img11.setImageResource(R.drawable.ic_s1);
                tx2.setTypeface(Typeface.DEFAULT);
                img2.setVisibility(View.INVISIBLE);

                tx3.setTypeface(Typeface.DEFAULT_BOLD);
                img3.setImageResource(R.drawable.ic_s2);
                img4.setVisibility(View.VISIBLE);

                status = 0;

                page = 1;
                name = "";
                goodsStatus = "4";
                loadGoods();
            } else {
                status = status == 0 ? 1 : 0;
                img3.setImageResource(status == 0 ? R.drawable.ic_s2 : R.drawable.ic_s3);

                page = 1;
                name = "";
                goodsStatus = status == 0 ? "4" : "5";
                loadGoods();
            }
        } else if (id == R.id.im_close) {
            editText.setText("");
        } else if (id == R.id.tx_cancel) {
            WindowInsetsControllerCompat controller = WindowCompat.getInsetsController(getWindow(), view);
            if (controller != null)
                controller.hide(WindowInsetsCompat.Type.ime());
            txCancel.setVisibility(View.GONE);
            editText.setText("");

            page = 1;
            name = "";
            loadGoods();
        }
    }

    private void loadGoods() {
        if (page==1){
            smartLayout.setEnableLoadMore(true);
        }
        smartLayout.finishRefresh();
        smartLayout.finishLoadMore();
        HttpUtil.api.getItemList(page, limit, GetMyInformationBox.INSTANCE.getMyId(), name, goodsStatus).enqueue(new Callback<Response<List<GoodsInfo>>>() {
            @Override
            public void onResponse(Call<Response<List<GoodsInfo>>> call, retrofit2.Response<Response<List<GoodsInfo>>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (page == 1) {
                        adapter.setData(response.body().getData());
                    } else {
                        adapter.addData(response.body().getData());
                    }
                    if (response.body().getData() == null || response.body().getData().size()<limit){
                        smartLayout.setEnableLoadMore(false);
                    }else{
                        page++;
                    }
                }else{
                    smartLayout.setEnableLoadMore(false);
                }
            }

            @Override
            public void onFailure(Call<Response<List<GoodsInfo>>> call, Throwable t) {
                smartLayout.setEnableLoadMore(false);
            }
        });
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        page = 1;
        smartLayout.setEnableLoadMore(true);
        loadGoods();
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        loadGoods();
    }


}
